//
//  YCFilterSelectionView.swift
//  YCCamera
//
//  Created by Billy on 2024/11/3.
//

import UIKit
import SnapKit

protocol YCFilterSelectionViewDelegate: AnyObject {
    func filterSelectionView(_ view: YCFilterSelectionView, didSelectFilter filterName: String)
}

class YCFilterSelectionView: UIView {
    
    weak var delegate: YCFilterSelectionViewDelegate?
    
    private var filterNames: [String] = []
    private var currentSelectedIndex: Int = 0
    
    private lazy var containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .black  // 与主界面一致
        view.layer.cornerRadius = 20   // 从底部弹出不需要圆角
        view.layer.masksToBounds = true
        return view
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .clear
        cv.showsHorizontalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
        cv.register(YCFilterCell.self, forCellWithReuseIdentifier: "YCFilterCell")
        cv.allowsSelection = true  // 确保允许选择
        cv.isUserInteractionEnabled = true  // 确保可交互
        return cv
    }()
    
    private lazy var closeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(systemName: "chevron.down"), for: .normal)
        button.tintColor = .white
        button.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        loadFilters()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = .clear  // 改为透明，让用户能看到滤镜效果
        
        addSubview(containerView)
        containerView.addSubview(collectionView)
        containerView.addSubview(closeButton)
        
        // 计算合适的高度：底部操作区域高度 + 安全区域高度（不要额外空间，避免遮挡画面）
        let bottomOperationHeight: CGFloat = 200  // YCCamera.Layout.bottomViewH
        let safeAreaHeight = BottomSafeHeight
        let totalHeight = bottomOperationHeight + safeAreaHeight  // 移除额外空间
        
        containerView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(totalHeight)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(120)
        }
        
        closeButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(collectionView.snp.bottom).offset(16)
            make.width.height.equalTo(40)
        }
        
        // 添加点击背景关闭的手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped(_:)))
        tapGesture.delegate = self
        addGestureRecognizer(tapGesture)
    }
    
    private func loadFilters() {
        filterNames = YCFilterManager.shared.getAllFilterNames()
        let currentFilter = YCFilterManager.shared.getCurrentFilterName()
        if let index = filterNames.firstIndex(of: currentFilter) {
            currentSelectedIndex = index
        }
        collectionView.reloadData()
        
        // 滚动到当前选中的滤镜
        DispatchQueue.main.async {
            self.collectionView.scrollToItem(
                at: IndexPath(item: self.currentSelectedIndex, section: 0),
                at: .centeredHorizontally,
                animated: false
            )
        }
    }
    
    @objc private func closeButtonTapped() {
        dismiss()
    }
    
    @objc private func backgroundTapped(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: self)
        if !containerView.frame.contains(location) {
            dismiss()
        }
    }
    
    func show(in view: UIView) {
        frame = view.bounds
        view.addSubview(self)
        
        // 每次显示时更新当前选中的滤镜状态
        updateCurrentSelection()
        
        // 计算滑入距离
        let bottomOperationHeight: CGFloat = 180
        let safeAreaHeight = BottomSafeHeight
        let totalHeight = bottomOperationHeight + safeAreaHeight
        
        // 初始位置：从底部外面
        containerView.transform = CGAffineTransform(translationX: 0, y: totalHeight)
        
        // 从底部滑入动画
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: .curveEaseOut) {
            self.containerView.transform = .identity
        }
    }
    
    // 更新当前选中的滤镜状态
    private func updateCurrentSelection() {
        let currentFilter = YCFilterManager.shared.getCurrentFilterName()
        if let index = filterNames.firstIndex(of: currentFilter) {
            let previousIndex = currentSelectedIndex
            currentSelectedIndex = index
            
            // 刷新相关的cell
            var indexPathsToReload: [IndexPath] = [IndexPath(item: currentSelectedIndex, section: 0)]
            if previousIndex != currentSelectedIndex {
                indexPathsToReload.append(IndexPath(item: previousIndex, section: 0))
            }
            
            collectionView.reloadItems(at: indexPathsToReload)
            
            // 滚动到当前选中的滤镜
            DispatchQueue.main.async {
                self.collectionView.scrollToItem(
                    at: IndexPath(item: self.currentSelectedIndex, section: 0),
                    at: .centeredHorizontally,
                    animated: true
                )
            }
        }
    }
    
    func dismiss() {
        // 计算滑出距离
        let bottomOperationHeight: CGFloat = 180
        let safeAreaHeight = BottomSafeHeight
        let totalHeight = bottomOperationHeight + safeAreaHeight
        
        // 滑出到底部
        UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseIn) {
            self.containerView.transform = CGAffineTransform(translationX: 0, y: totalHeight)
        } completion: { _ in
            // 只从父视图移除，不销毁对象，以便复用
            self.removeFromSuperview()
        }
    }
}

// MARK: - UICollectionViewDelegate & DataSource
extension YCFilterSelectionView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return filterNames.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YCFilterCell", for: indexPath) as! YCFilterCell
        let filterName = filterNames[indexPath.item]
        let isSelected = indexPath.item == currentSelectedIndex
        cell.configure(with: filterName, isSelected: isSelected)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 75, height: 95)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("🎯 点击了滤镜: \(filterNames[indexPath.item])")
        
        // 更新选中状态
        let previousIndex = currentSelectedIndex
        currentSelectedIndex = indexPath.item
        
        // 刷新cell
        collectionView.reloadItems(at: [IndexPath(item: previousIndex, section: 0), indexPath])
        
        // 滚动到选中项
        collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        
        // 切换滤镜
        let filterName = filterNames[indexPath.item]
        YCFilterManager.shared.setFilter(by: filterName)
        
        // 通知代理，让YCCamera触发画面更新
        delegate?.filterSelectionView(self, didSelectFilter: filterName)
        
        // 不再自动关闭，让用户可以连续切换滤镜对比效果
        // 用户需要点击关闭按钮或点击背景区域来关闭
    }
}

// MARK: - UIGestureRecognizerDelegate
extension YCFilterSelectionView: UIGestureRecognizerDelegate {
    override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        // 如果点击的是containerView内部，不响应手势，让collectionView接收点击
        if touch.view?.isDescendant(of: containerView) == true {
            return false
        }
        return true
    }
}

// MARK: - YCFilterCell
class YCFilterCell: UICollectionViewCell {
    
    private lazy var thumbnailView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white.withAlphaComponent(0.08)
        view.layer.cornerRadius = 10
        view.layer.masksToBounds = true
        return view
    }()
    
    private lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 13, weight: .medium)
        label.textColor = .white.withAlphaComponent(0.7)
        label.textAlignment = .center
        return label
    }()
    
    private lazy var selectionIndicator: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 1.5
        view.alpha = 0
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
        // 完全禁用系统默认的选中效果
        selectedBackgroundView = nil
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(thumbnailView)
        contentView.addSubview(nameLabel)
        contentView.addSubview(selectionIndicator)
        
        thumbnailView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.centerX.equalToSuperview()
            make.width.height.equalTo(65)
        }
        
        nameLabel.snp.makeConstraints { make in
            make.top.equalTo(thumbnailView.snp.bottom).offset(8)
            make.left.right.equalToSuperview()
        }
        
        selectionIndicator.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(nameLabel.snp.bottom).offset(4)
            make.width.equalTo(20)
            make.height.equalTo(3)
        }
    }
    
    func configure(with filterName: String, isSelected: Bool) {
        nameLabel.text = filterName
        
        UIView.animate(withDuration: 0.2) {
            if isSelected {
                // 添加绿色边框
                self.thumbnailView.layer.borderWidth = 2
                self.thumbnailView.layer.borderColor = UIColor.systemGreen.cgColor
                self.thumbnailView.backgroundColor = UIColor.white.withAlphaComponent(0.15)
                self.thumbnailView.transform = CGAffineTransform(scaleX: 1.05, y: 1.05)
                self.nameLabel.textColor = .systemGreen
                self.nameLabel.font = .systemFont(ofSize: 13, weight: .semibold)
                self.selectionIndicator.alpha = 1
                self.selectionIndicator.backgroundColor = .systemGreen
            } else {
                // 移除边框
                self.thumbnailView.layer.borderWidth = 0
                self.thumbnailView.layer.borderColor = UIColor.clear.cgColor
                self.thumbnailView.backgroundColor = UIColor.white.withAlphaComponent(0.08)
                self.thumbnailView.transform = .identity
                self.nameLabel.textColor = .white.withAlphaComponent(0.7)
                self.nameLabel.font = .systemFont(ofSize: 13, weight: .medium)
                self.selectionIndicator.alpha = 0
                self.selectionIndicator.backgroundColor = .white
            }
        }
    }
}

